<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">

          <el-form-item label="门店名称：">
            <el-input v-model="listQuery.storeName"
                      placeholder="请输入"
                      clearable @change="handleFilter"/>
          </el-form-item>


        </div>
        <div class="right-box">
          <el-button size="mini" type="success"
                     @click="handleCreate">新增
          </el-button>

          <el-button size="mini"
                     @click="handleFilter">查询
          </el-button>
          <el-button size="mini" type="info"
                     @click="reset">重置
          </el-button>
        </div>
      </template>
    </search-box>
    <div class="table-wrap">
      <el-table :data="list"
                style="width:100%"
                element-loading-text="Loading"
                height="600">
        <el-table-column
          type="index"
          width="50"
          label="序号"
        ></el-table-column>
        <el-table-column prop="storeCode"
                         label="门店编码" width="100">
        </el-table-column>

        <el-table-column prop="storeName"
                         label="门店名称" width="200">
        </el-table-column>
        <el-table-column prop="address"
                         label="门店地址" width="400">
          <template slot-scope="scope">
            <div >
              {{scope.row.address.replaceAll(' ','')}}
            </div>
          </template>

        </el-table-column>

        <el-table-column prop="linkPeople"
                         label="联系人" width="100">
        </el-table-column>
        <el-table-column prop="linkTel"
                         label="联系电话" width="200">
        </el-table-column>
        <el-table-column prop="isOpen"
                         label="是否开业" width="100">
          <template slot-scope="scope">
            <div >
              <span v-if="scope.row.isOpen==1" style="color: green">
                是
              </span>
              <span v-else style="color: red">
                否
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="storeLongitude"
                         label="经度" width="100">
        </el-table-column>
        <el-table-column prop="storeLatitude"
                         label="纬度" width="100">
        </el-table-column>
<!--        <el-table-column prop="createDate"-->
<!--                         label="创建时间">-->
<!--        </el-table-column>-->
        <el-table-column label="操作"
                         width="200">
          <template slot-scope="scope">
            <div class="scope-operate">
              <el-button type="info" size="mini" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除
              </el-button>

            </div>
          </template>
        </el-table-column>


      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList"/>
    </div>


    <!--    //dialog弹窗 在页面的最后一个</div>的上面-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="60%"
      style="margin-top: -5%"
      :before-close="handleClose"
      >
      <el-form ref="form" :model="form" :rules = 'rules' label-width="120px">

        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item label="门店编码" prop="storeCode">
              <el-input v-model="form.storeCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店名称" prop="storeName">
              <el-input v-model="form.storeName"></el-input>
            </el-form-item>
          </el-col>
          </el-form-item>


        <el-form-item label-width="0">
          <el-col :span="5">
            <el-form-item label="省份" prop="provinceName">

              <el-select v-model="form.provinceName" placeholder="请选择" @change="getCityInfoList" id="provinceName">
                <el-option
                  v-for="item in areaInfoList"
                  :key="item.areaName"
                  :label="item.areaName"
                  :value="item.areaName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="城市" prop="cityName">
              <el-select v-model="form.cityName" placeholder="请选择" @change="getCountyInfoList" id="cityName">
                <el-option
                  v-for="item in cityInfoList"
                  :key="item.areaName"
                  :label="item.areaName"
                  :value="item.areaName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="区划" prop="countyName">
              <el-select v-model="form.countyName" placeholder="请选择" id="countyName">
                <el-option
                  v-for="item in countyInfoList"
                  :key="item.areaName"
                  :label="item.areaName"
                  :value="item.areaName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input v-model="form.detailAddress"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label-width="0">
          <el-col :span="9">
            <el-form-item label="联系人" prop="linkPeople">
              <el-input v-model="form.linkPeople"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="9">
            <el-form-item label="联系电话" prop="linkTel">
              <el-input v-model="form.linkTel"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否开业" prop="isOpen">
              <el-select v-model="form.isOpen" placeholder="请选择">
                <el-option label="是" :value="1" checked="checked"></el-option>
                <el-option label="否" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          </el-form-item>
        <el-form-item label="业务描述" prop="storeBusiness">
          <el-input v-model="form.storeBusiness"></el-input>
        </el-form-item>

        <el-form-item label="门店logo" prop="storeLogo" >
          <el-upload
            class="avatar-uploader"
            :action="processBaseUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>


        <el-form-item label="门店照片" prop="storeImage">
          <el-upload
            class="upload-demo"
            :action="processBaseUrl"
            :on-success="handleSuccess"
            :file-list="fileList"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible1">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item label="经度" prop="storeLongitude">
              <el-input v-model="form.storeLongitude"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="storeLatitude">
              <el-input v-model="form.storeLatitude"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
<!--        <el-form-item label="经度" prop="storeLongitude">-->
<!--          <el-input v-model="form.storeLongitude"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="纬度" prop="storeLatitude">-->
<!--          <el-input v-model="form.storeLatitude"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提 交</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">

  </span>
    </el-dialog>


  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import bus from '@/utils/eventBus'
  import searchBox from '@/components/searchBox.vue'
  import * as store from '@/api/store/store'
  import * as areaInfo from '@/api/area/areaInfo'
  export default {
    name: 'AdminUser',
    components: { Pagination, searchBox },
    directives: { waves },
    filters: {},
    data() {
      return {
        dialogVisible1: false,
        dialogImageUrl: '',
        list: null,
        areaInfoList: null,
        cityInfoList: null,
        countyInfoList: null,
        areaList: null,
        total: 0,
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          pageSize: 50,
          appName: process.env.VUE_APP_APP_NAME,
          tenantIdList: []
        },
        dialogVisible: false,
        dialogTitle:'',
        form:{

          isOpen:1,
          provinceName:'',
          cityName:'',
          countyName:'',
          detailAddress: '',
        },

        processBaseUrl: process.env.VUE_APP_BASE_API+'/file/upload',
        fileList: [],
        imageUrl:'',
        rules: {
          storeCode: [{ required: true, message: '门店编码必填', trigger: 'blur' }],
          storeBusiness: [{ required: true, message: '门店业务必填', trigger: 'blur' }],
          storeName: [{ required: true, message: '门店名称必填', trigger: 'blur' }],
          linkPeople: [{ required: true, message: '联系人必填', trigger: 'blur' }],
            linkTel: [{ required: true, message: '联系人电话必填', trigger: 'blur' }],
          isOpen: [{ required: true, message: '门店是否开放必填', trigger: 'blur' }],
          provinceName: [{ required: true, message: '省份必选', trigger: 'blur' }],
          cityName: [{ required: true, message: '城市必选', trigger: 'blur' }],
          countyName: [{ required: true, message: '区划必选', trigger: 'blur' }],
          detailAddress: [{ required: true, message: '详细地址必填', trigger: 'blur' }],
          storeImage: [{ required: true, message: '门店照片必上传', trigger: 'blur' }],
          storeLogo: [{ required: true, message: '门店logo必上传', trigger: 'blur' }],
        },
        address:'',
      }
    },
    computed: {
      ...mapGetters([
        'selectedTenantId',
        'tenantList'
      ])
    },
    created() {

      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.getList()

      // 监听 租户改变的事件,选择不同租户后,立马刷新数据
      bus.$on('selectedTenantIdChanged', () => {
        console.log('selectedTenantIdChanged事件触发...')
        this.getList()
      })
    },
    mounted() {
      // 测试用
      // var that = this
      // setTimeout(function() {
      //   that.dialogFormVisible = true
      // }, 5000)
    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      bus.$off('selectedTenantIdChanged')
    },
    methods: { //所有的方法写在当前钩子函数下

      async getList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await store.getStoreList(this.listQuery)
        this.list = content.list
        this.total = content.totalCounts
      },
      async getAreaInfoList() { // 获取省列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }

        let query = {}
        const { content } = await areaInfo.getAreaInfoListNoPage(query);
        this.areaInfoList = content; //分页的时候是content.list;不分页的时候是content 因为不分页的时候少封装一层
        query  = {};
      },

      async getCityInfoList() { // 获取市列表数据


        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }

        let query  = {};
        if(this.form.provinceName!=null){
          query.parentName = this.form.provinceName;
        }

        const { content } = await areaInfo.getAreaInfoListNoPage(query);
        this.cityInfoList = content; //分页的时候是content.list;不分页的时候是content 因为不分页的时候少封装一层
        query  = {};
      },

      async getCountyInfoList() { // 获取区列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }

        let query  = {};
        if(this.form.cityName!=null){
          query.parentName = this.form.cityName;
        }
        const { content } = await areaInfo.getAreaInfoListNoPage(query);
        this.countyInfoList = content; //分页的时候是content.list;不分页的时候是content 因为不分页的时候少封装一层
        query  = {};
      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },


      handleClose(){
        this.dialogVisible = false;
        this.fileList=[];
        this.imageUrl='';

      },

      //新增数据
      handleCreate() {
        this.form={}
        this.dialogVisible = true
        this.dialogTitle='新增'
        this.form.provinceCode = null
        this.getAreaInfoList();
      },
      //编辑数据
      handleUpdate(row) {

        this.dialogVisible = true
        this.dialogTitle='编辑';
        this.form = row;
        this.getAreaInfoList();
        let address = row.address.split(" ");
        this.$set(this.form,'provinceName',address[0]);
        this.$set(this.form,'cityName',address[1]);
        this.$set(this.form,'countyName',address[2]);
        this.$set(this.form,'detailAddress',address[3]);
        if(row.storeImage!=null&&row.storeImage!=''){
        let fileUrl = row.storeImage.split(",");
        let proFileName = row.storeImage.split(",");


        for(let i = 0;i<fileUrl.length;i++){
          let imageInfo = {

          }
          imageInfo.url=process.env.VUE_APP_BASE_API+'/file/downloadFile?fileName='+fileUrl[i]
          imageInfo.name=proFileName[i]
          this.fileList.push(imageInfo);
        }
        }else{
          this.fileList=[]
        }

        if(row.storeLogo!=null&&row.storeLogo!=''){
          this.imageUrl = process.env.VUE_APP_BASE_API+'/file/downloadFile?fileName='+row.storeLogo;
        }else{
          this.imageUrl='';
        }


      },
      //删除数据
      handleDelete(row) {

        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.deleteStore(row).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
        })
      },


      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },


      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

      handleSuccess(response, file, fileList) {

        console.log(this.fileList);
        console.log('文件成功列表',fileList);
        let proUrl = '';
        let proFileName = '';
        for(let i = 0;i<fileList.length;i++){
          proUrl+=(fileList[i].response.uuid+',')
          proFileName+=(fileList[i].response.name+',')
        }
        this.form.storeImage = proUrl.substring(0,proUrl.length-1)
        // this.form.proFileName = proFileName.substring(0,proFileName.length-1)
      },


      handleAvatarSuccess(res, file) {
        console.log(file);
        this.imageUrl = URL.createObjectURL(file.raw);
        this.form.storeLogo = file.response.uuid;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },


      //页面表单提交
      onSubmit(){

        let provinceName =null;
        let cityName =null;
        let countyName =null;
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.form.tenantId = this.$store.getters.selectedTenantId
            debugger


            //根据id进行取值操作
             provinceName =  document.getElementById("provinceName").value;
             cityName =  document.getElementById("cityName").value;
             countyName =  document.getElementById("countyName").value;


            this.form.address='';
            if(provinceName!=null||provinceName!=undefined){
              this.form.address += (provinceName+" ");
            }
            if(cityName!=null||cityName!=undefined){
              this.form.address += (cityName+" ");
            }
            if(countyName!=null||countyName!=undefined){
              this.form.address += (countyName+" ");
            }
            if(this.form.detailAddress!=null||this.form.detailAddress!=undefined){
              this.form.address += this.form.detailAddress;
            }
            if (this.dialogTitle == '新增') {
              store.createStore(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.dialogVisible = false
                  this.getList()

                }
              })

            } else if (this.dialogTitle == '编辑') {

              store.updateStore(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '编辑成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.dialogVisible = false
                  this.getList()

                }
              })


            }

             provinceName =  null
             cityName =  null
             countyName =  null

          } else {
            console.log('error submit!!')
            return false
          }
        })


      },
      cancel(){
        this.dialogVisible = false;
        this.form = {};
        this.fileList=[];
      },
      reset() {
        this.listQuery = {}
        this.getList()
      }
    }
  }
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }
</style>
